<?php

namespace App\Http\Controllers\Admin;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class GoodsController extends BaseController{
    //商品管理

    //--------------------商品列表---------------------
    public function index(Request $request){
        $method=$request->method();
        if ($method=='POST'){
            $data=$request->all();
            $where['type']=1;
            $list=DB::table('goods')->where($where)->orderByDesc('goods_sort')->paginate(15);

            if (!is_null($data['goods_name'])){
             $where[] = ['goods_name','like','%'.trim($data['goods_name']).'%'];
             $list=DB::table('goods')->where($where)->orderByDesc('goods_sort')->paginate(15);
            }

            if (!is_null($data['category_id'])){
            	$map[] = ['name','like','%'.trim($data['category_id']).'%'];
            	$cate=DB::table('goods_cate')->where($map)->first();
            	if($cate){
               $where['category_id']=$cate->id;
               $list=DB::table('goods')->where($where)->orderByDesc('goods_sort')->paginate(15);
            	}
            }


              if (!is_null($data['goods_name']) && !is_null($data['category_id'])){
             $where[] = ['goods_name','like','%'.trim($data['goods_name']).'%'];
             $map[] = ['name','like','%'.trim($data['category_id']).'%'];
             $cate=DB::table('goods_cate')->where($map)->first();
             if($cate){
             $where['category_id']=$cate->id;
             }
             $list=DB::table('goods')->where($where)->orderByDesc('goods_sort')->paginate(15);

            }


        }else{
            $list=DB::table('goods')->where('type',1)->orderByDesc('goods_sort')->paginate(15);
        }


        foreach ($list as $k=>$v){
            $list[$k]->create_time=date('Y-m-d H:i:s',$v->create_time);
            $list[$k]->image=$this->GetGoodsImg($v->goods_id);
            $list[$k]->category_id=$this->GetCate($v->category_id);
        }
        return view('goods.index',compact('list'));
    }


    //添加商品
    public function addgoods(Request $request){
        $method=$request->method();
        if ($method=='POST') {
            //开启事务,添加商品信息
            DB::beginTransaction();
            try{
            $data=$request->input('goods');
            
             if(isset($data['coupon_id'])){
           	$data['coupon_id']=json_encode($data['coupon_id']);
            }
            $data['create_time']=time();
            $data['collage_time']=strtotime($data['collage_time']);
            unset($data['time']);
            $res=DB::table('goods')->insertGetId($data);
            $goods_id=$res;

            /*---------所有图片集合-----------*/
            $arr=$request->input('image_id');
            foreach ($arr as $v){
                $img['goods_id']=$goods_id;
                $img['image_id']=$v;
                DB::table('goods_image')->insert($img);
            }

            /*---------所有规格集合-----------*/
            $goods_sku=$request->input('sku');
            foreach ($goods_sku['goods_sku'] as $k=>$v){
                $sku['goods_id']=$goods_id;
                $sku['goods_sku']=$v;
                $sku['image']= $goods_sku['image'][$k];
                $sku['goods_price']= $goods_sku['goods_price'][$k];
                $sku['line_price']= $goods_sku['line_price'][$k];
                $sku['stock_num']= $goods_sku['stock_num'][$k];
                $sku['goods_weight']= $goods_sku['goods_weight'][$k];
                DB::table('goods_sku')->insert($sku);
            }
            DB::commit();
            return json_encode(['code'=>1,'msg'=>'添加成功']);
            }catch (\Exception $e) {
            DB::rollBack();
            return json_encode(['code'=>0,'msg'=>'添加失败']);
            }
        }

        $cate=DB::table('goods_cate')->where('parent_id',0)->get(['id','name'])->each(function ($item,$key){
            $result=DB::table('goods_cate')->where('parent_id',$item->id)->get(['id','name']);
            if (!$result->isEmpty()) {
              $item->child=$result;
            }
            return $item;
        });
        
        
        $coupon=DB::table('coupon')->get();
        $setseckill=DB::table('setseckill')->get();
        return view('goods.addgoods',compact('cate','coupon','setseckill'));
    }

    //编辑商品
    public function editgoods(Request $request){
        $method=$request->method();
        $goods_id=$request->route('id');
        if ($method=='POST') {
            //开启事务,,更新商品信息
            DB::beginTransaction();
            try{
            $data=$request->input('goods');
            
            if(isset($data['coupon_id'])){
           	$data['coupon_id']=json_encode($data['coupon_id']);
            }
            
            
            $data['collage_time']=strtotime($data['collage_time']);
            $data['create_time']=time();

            $datearray=explode(' - ',$data['time']);
            $data['seckill_start']=strtotime($datearray[0]);
            $data['seckill_end']=strtotime($datearray[1]);
            unset($data['time']);
            DB::table('goods')->where('goods_id',$goods_id)->update($data);

            $arr=$request->input('image_id');//所有图片集合
            $imgarr=$request->input('imgarr');//数据中的图片集合

            foreach ($arr as $k=>$v){
                if (!isset($imgarr[$k])){
                    $img['goods_id']=$goods_id;
                    $img['image_id']=$v;
                    DB::table('goods_image')->insert($img);
                }
            }

            //所有规格集合
            $goods_sku=$request->input('sku');
            foreach ($goods_sku['goods_sku'] as $k=>$v){
            	
            	    $sku['goods_id']=$goods_id;
                    $sku['goods_sku']=$v;
                    $sku['goods_price']= $goods_sku['goods_price'][$k];
                    $sku['line_price']= $goods_sku['line_price'][$k];
                    $sku['stock_num']= $goods_sku['stock_num'][$k];
                    $sku['goods_weight']= $goods_sku['goods_weight'][$k];
                    $sku['image']= $goods_sku['image'][$k];
                //更新规格
                if (isset($goods_sku['sku_id'][$k])){
                    DB::table('goods_sku')->where('id',$goods_sku['sku_id'][$k])->update($sku);
                }else{
                    //添加新的规格
                    DB::table('goods_sku')->insert($sku);
                }
            }
             DB::commit();
             return json_encode(['code'=>1,'msg'=>'更新成功']);
            }catch (\Exception $e) {
             DB::rollBack();
             return json_encode(['code'=>0,'msg'=>'更新失败']);
            }

        }

        $list=DB::table('goods')->where('goods_id',$goods_id)->first();
        $img=DB::table('goods_image')->where('goods_id',$list->goods_id)->get();
        $sku=DB::table('goods_sku')->where('goods_id',$list->goods_id)->get();
        foreach ($img as $k=>$v){
            $img[$k]->url=$this->GetImg($v->image_id);
        }

        foreach ($sku as $k=>$v){
            $sku[$k]->url=$this->GetImg($v->image);
        }

           $cate=DB::table('goods_cate')->where('parent_id',0)->get(['id','name'])->each(function ($item,$key){
            $result=DB::table('goods_cate')->where('parent_id',$item->id)->get(['id','name']);
            if (!$result->isEmpty()) {
              $item->child=$result;
            }
            return $item;
        });

        $coupon=DB::table('coupon')->get();
        $setseckill=DB::table('setseckill')->get();
        return view('goods.editgoods',compact('list','cate','img','sku','coupon','setseckill'));
    }


    //删除商品规格
    public function delsku(Request $request){
        $id=(int)($request->input('id'));
        $res=DB::table('goods_sku')->delete($id);
        if ($res){
            $data=['code'=>1,'msg'=>'删除成功'];
        }else{
            $data=['code'=>0,'msg'=>'删除失败'];
        }
        return json_encode($data);
    }

    //删除商品
    public function delgoods(Request $request){
        $id=(int)($request->input('id'));
        DB::beginTransaction();
        $res=DB::table('goods')->where('goods_id',$id)->delete();
        DB::table('goods_sku')->where('goods_id',$id)->delete();
        DB::table('goods_image')->where('goods_id',$id)->delete();
        DB::commit();  //提交
        if ($res){
            $data=['code'=>1,'msg'=>'删除成功'];
        }else{
            $data=['code'=>0,'msg'=>'删除失败'];
        }
        return json_encode($data);
    }

    //删除商品图片
    public function delgoodsimg(Request $request){
        $id=(int)($request->input('image_id'));
        $res=DB::table('goods_image')->where('image_id',$id)->delete();
        if ($res){
            $data=['code'=>1,'msg'=>'删除成功'];
        }else{
            $data=['code'=>0,'msg'=>'删除失败'];
        }
        return json_encode($data);
    }

    //------------商品分类-----------------------------
    //商品分类
    public function category(){
        $list=DB::table('goods_cate')->where('parent_id',0)->get()->each(function ($item,$key){
            $result=DB::table('goods_cate')->where('parent_id',$item->id)->get();
            if (!$result->isEmpty()) {
              $item->child=$result;
            }
            return $item;
        });

        return view('goods.category',compact('list'));
    }

    public function GetCate($id){
        $list=DB::table('goods_cate')->find($id);
        return $list->name;

    }

    //添加商品分类
    public function addcategory(Request $request){
        $method=$request->method();
        if ($method=='POST') {
            $data=$request->all();
            unset($data['_token']);
            $data['create_time']=time();
            $res=DB::table('goods_cate')->insert($data);
            if(!empty($res)){
                $data=['code'=>1,'msg'=>'添加成功'];
            }else{
                $data=['code'=>0,'msg'=>'添加失败'];
            }
            return json_encode($data);
        }


           $cate=DB::table('goods_cate')->where('parent_id',0)->get(['id','name'])->each(function ($item,$key){
            $result=DB::table('goods_cate')->where('parent_id',$item->id)->get(['id','name']);
            if (!$result->isEmpty()) {
              $item->child=$result;
            }
            return $item;
        });

        return view('goods.addcategory',compact('cate'));
    }



    //编辑商品分类
    public function editcategory(Request $request){
        $method=$request->method();
        $id=$request->route('id');
        if ($method=='POST') {
            $data=$request->all();
            unset($data['_token']);
            $data['create_time']=time();
            $res=DB::table('goods_cate')->where('id',$id)->update($data);
            if(!empty($res)){
                $data=['code'=>1,'msg'=>'更新成功'];
            }else{
                $data=['code'=>0,'msg'=>'更新失败'];
            }
            return json_encode($data);
        }
        $list=DB::table('goods_cate')->find($id);

            $cate=DB::table('goods_cate')->where('parent_id',0)->get(['id','name'])->each(function ($item,$key){
            $result=DB::table('goods_cate')->where('parent_id',$item->id)->get(['id','name']);
            if (!$result->isEmpty()) {
              $item->child=$result;
            }
            return $item;
        });

        return view('goods.editcategory',compact('list','cate'));
    }


    //删除商品分类
    public function delcategory(Request $request){
        $id=(int)($request->input('id'));

        //检查是否有子类
        $check=DB::table('goods_cate')->where('parent_id',$id)->first();
        if ($check){
            $data=['code'=>0,'msg'=>'不能删除，该分类下有子类'];
            return json_encode($data);
        }
         //检查是否有商品
        $checkgoods=DB::table('goods')->where('category_id',$id)->first();
        if ($checkgoods){
            $data=['code'=>0,'msg'=>'不能删除，该分类下有商品'];
            return json_encode($data);
        }

        $res=DB::table('goods_cate')->delete($id);
        if ($res){
            $data=['code'=>1,'msg'=>'删除成功'];
        }else{
            $data=['code'=>0,'msg'=>'删除失败'];
        }
        return json_encode($data);
    }

    //-----------------------------------------

    //商品评价列表
    public function comment(){
        $list=DB::table('comment')->paginate(15);
        foreach ($list as $k=>$v){
            $list[$k]->goods=$this->Getgoods($v->goods_id);
        }

        return view('goods.comment',compact('list'));
    }

    //获取商品详情
    public function Getgoods($goods_id){
        $list=DB::table('goods')->where('goods_id',$goods_id)->first();
        $list->image=$this->GetGoodsImg($list->goods_id);
        return $list;
    }

    //评价详情
    public function commentdetail($id){
        $list=DB::table('comment')->where('comment_id',$id)->first();
        $list->goods=$this->Getgoods($list->goods_id);

        return view('goods.detail',compact('list'));
    }

    //删除商品评价
    public function del(Request $request){
        $comment_id=$request->input('id');
        $res=DB::table('comment')->where('comment_id',$comment_id)->delete();
        if ($res){
            $data=['code'=>1,'msg'=>'删除成功'];
        }else{
            $data=['code'=>0,'msg'=>'删除失败'];
        }
        return json_encode($data);
    }

    //商品评价状态
    public function status(Request $request){
        $comment_id=$request->input('id');
        $update['status']=$request->input('status');
        $res=DB::table('comment')->where('comment_id',$comment_id)->update($update);
        if ($res){
            $data=['code'=>1,'msg'=>'操作成功'];
        }else{
            $data=['code'=>0,'msg'=>'操作失败'];
        }
        return json_encode($data);

    }


}
